<?php
/**
 * Created by PhpStorm.
 * excel导出类
 * User: lizhuang
 * Date: 2015/3/28
 * Time: 15:48
 */

class CSVLIB {

    function export_csv(&$data, $title_arr, $file_name = '') {
        ini_set("max_execution_time", "3600");

        $csv_data = '';

        /** 标题 */
        $nums = count($title_arr);
        for ($i = 0; $i < $nums - 1; ++$i) {
            $csv_data .= '"' . $title_arr[$i] . '",';
        }

        if ($nums > 0) {
            $csv_data .= '"' . $title_arr[$nums - 1] . "\"\r\n";
        }

        foreach ($data as $k => $row) {
            for ($i = 0; $i < $nums - 1; ++$i) {
                $row[$i] = str_replace("\"", "\"\"", $row[$i]);
                $csv_data .= '"' . $row[$i] . '",';
            }
            $csv_data .= '"' . $row[$nums - 1] . "\"\r\n";
            unset($data[$k]);
        }

//        $csv_data = mb_convert_encoding($csv_data, "cp936", "UTF-8");
        $csv_data=mb_convert_encoding($csv_data,"gb2312","auto");
        $file_name = empty($file_name) ? date('Y-m-d-H-i-s', time()) : $file_name;

        if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE")) { // 解决IE浏览器输出中文名乱码的bug
            $file_name = urlencode($file_name);
            $file_name = str_replace('+', '%20', $file_name);
        }

        $file_name = $file_name . '.csv';
        header("Content-type:text/csv;");
        header("Content-Disposition:attachment;filename=" . $file_name);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo $csv_data;
    }

}
